import { Component, OnInit } from "@angular/core";
import { MaterialManagementPlatformService } from "../../proxy/joy/erp/ufida/pmc";
import { 
  MaterialBalanceAnalysisDto, 
  GetMaterialBalanceInput,
  SupplyDemandRecordDto,
  DailyBalanceDto
} from "../../proxy/joy/erp/ufida/pmc/models";
import * as XLSX from 'xlsx';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'lib-material-management-platform',
  templateUrl: './material-management-platform.component.html',
  styleUrls: ['./material-management-platform.component.less'],
})
export class MaterialManagementPlatformComponent implements OnInit {
  
  dataList: MaterialBalanceAnalysisDto[] = [];
  totalCount = 0;
  loading = false;
  exporting = false;
  cutoffDate: Date = new Date();
  pageIndex = 1;
  pageSize = 10;
  
  // 选中的料品详情
  selectedMaterial: MaterialBalanceAnalysisDto | null = null;
  selectedMaterialIndex: number = -1;
  
  // 缓存日期列表，确保表头和数据行使用相同的日期列表
  private cachedDates: string[] = [];
  
  constructor(
    private materialManagementService: MaterialManagementPlatformService,
    private message: NzMessageService
  ) {}

  ngOnInit() {
    // 设置默认截止日期为30天后
    this.cutoffDate = new Date();
    this.cutoffDate.setDate(this.cutoffDate.getDate() + 30);
  }

  onQuery(forceRefresh: boolean = false) {
    if (!this.cutoffDate) {
      return;
    }

    this.loading = true;
    this.selectedMaterial = null;
    this.selectedMaterialIndex = -1;

    const skipCount = (this.pageIndex - 1) * this.pageSize;

    const input: GetMaterialBalanceInput = {
      cutoffDate: this.cutoffDate.toISOString(),
      itemCode: undefined,
      itemMasterIds: [],
      includeSafetyStockWarning: true,
      onlyShowShortage: false,
      forceRefresh: forceRefresh,
      skipCount: skipCount,
      maxResultCount: this.pageSize,
      sorting: undefined
    };

    this.materialManagementService.getMaterialBalanceAnalysis(input).subscribe({
      next: (result) => {
        this.totalCount = result.totalCount || 0;
        this.dataList = result.items || [];
        // 更新日期缓存
        this.updateDateCache();
        this.loading = false;
        console.log('数据加载完成:', { 
          totalCount: this.totalCount,
          currentPage: this.pageIndex,
          pageSize: this.pageSize,
          cutoffDate: this.cutoffDate,
          dates: this.cachedDates
        });
      },
      error: () => {
        this.loading = false;
      }
    });
  }

  onReset() {
    this.cutoffDate = new Date();
    this.cutoffDate.setDate(this.cutoffDate.getDate() + 30);
    this.dataList = [];
    this.totalCount = 0;
    this.pageIndex = 1;
    this.selectedMaterial = null;
    this.selectedMaterialIndex = -1;
    this.cachedDates = [];
  }

  onSelectMaterial(material: MaterialBalanceAnalysisDto, index: number) {
    if (this.selectedMaterialIndex === index) {
      // 再次点击同一行，收起详情
      this.selectedMaterial = null;
      this.selectedMaterialIndex = -1;
    } else {
      this.selectedMaterial = material;
      this.selectedMaterialIndex = index;
    }
  }

  onPageIndexChange(pageIndex: number): void {
    this.pageIndex = pageIndex;
    this.onQuery(false);
  }

  onPageSizeChange(pageSize: number): void {
    this.pageSize = pageSize;
    this.pageIndex = 1; // 重置到第一页
    this.onQuery(false);
  }

  // 更新日期缓存
  private updateDateCache(): void {
    if (!this.dataList || this.dataList.length === 0) {
      this.cachedDates = [];
      return;
    }

    const dateSet = new Set<string>();
    this.dataList.forEach(item => {
      if (item.dailyBalances) {
        item.dailyBalances.forEach(daily => {
          if (daily.date) {
            dateSet.add(daily.date);
          }
        });
      }
    });

    this.cachedDates = Array.from(dateSet).sort();
  }

  // 获取所有日期列（用于表头和数据行）
  getAllDates(): string[] {
    return this.cachedDates;
  }

  // 根据日期获取每日数据
  getDailyData(material: MaterialBalanceAnalysisDto, date: string): DailyBalanceDto | null {
    if (!material.dailyBalances) {
      return null;
    }
    
    const daily = material.dailyBalances.find(d => d.date === date);
    return daily || null;
  }

  // 获取期内数据（直接从 material 对象获取）
  getWithinPeriodData(material: MaterialBalanceAnalysisDto): any {
    return {
      withinPeriodStock: material.withinPeriodStock || 0,
      withinPeriodTotalSupply: material.withinPeriodTotalSupply || 0,
      withinPeriodTotalDemand: material.withinPeriodTotalDemand || 0,
      isShortage: material.isWithinPeriodShortage,
      shortageQuantity: material.withinPeriodMaxShortageQuantity
    };
  }

  // 获取期外数据（直接从 material 对象获取）
  getOutOfPeriodData(material: MaterialBalanceAnalysisDto): any {
    return {
      outOfPeriodStock: material.outOfPeriodStock || 0,
      outOfPeriodTotalSupply: material.outOfPeriodTotalSupply || 0,
      outOfPeriodTotalDemand: material.outOfPeriodTotalDemand || 0,
      isShortage: material.isOutOfPeriodShortage,
      shortageQuantity: material.outOfPeriodMaxShortageQuantity
    };
  }

  // 格式化日期显示
  formatDate(dateStr?: string): string {
    if (!dateStr) return '';
    return dateStr.split('T')[0];
  }

  // 获取供需类型显示文本
  getSupplyDemandTypeText(type: number): string {
    return type === 1 ? '供应' : '需求';
  }

  // 计算统计数据（用于详情页面顶部）
  getSupplyStats(material: MaterialBalanceAnalysisDto): any {
    if (!material.supplyDemandRecords) {
      return {
        totalSupply: 0,
        totalDemand: 0,
        purchaseOrderQty: 0,
        asnQty: 0
      };
    }

    const stats = {
      totalSupply: 0,
      totalDemand: 0,
      purchaseOrderQty: 0,
      asnQty: 0
    };

    material.supplyDemandRecords.forEach(record => {
      if (record.type === 1) { // 供应
        stats.totalSupply += record.pendingQuantity;
        if (record.docType === '采购订单') {
          stats.purchaseOrderQty += record.pendingQuantity;
        } else if (record.docType === 'ASN单') {
          stats.asnQty += record.pendingQuantity;
        }
      } else { // 需求
        stats.totalDemand += record.pendingQuantity;
      }
    });

    return stats;
  }

  // 导出Excel
  onExport() {
    if (!this.cutoffDate) {
      this.message.warning('请先选择截止日期');
      return;
    }

    this.exporting = true;

    // 获取所有数据（设置一个很大的maxResultCount）
    const input: GetMaterialBalanceInput = {
      cutoffDate: this.cutoffDate.toISOString(),
      itemCode: undefined,
      itemMasterIds: [],
      includeSafetyStockWarning: true,
      onlyShowShortage: false,
      forceRefresh: false,
      skipCount: 0,
      maxResultCount: 999999, // 获取所有数据
      sorting: undefined
    };

    this.materialManagementService.getMaterialBalanceAnalysis(input).subscribe({
      next: (result) => {
        const allData = result.items || [];
        
        if (allData.length === 0) {
          this.message.warning('没有数据可导出');
          this.exporting = false;
          return;
        }

        // 准备导出数据
        const exportData = allData.map((item, index) => {
          const row: any = {
            '序号': index + 1,
            '料号': item.itemCode || '',
            '料品名称': item.itemName || '',
            '规格型号': item.itemSpec || '',
            '单位': item.uom || '',
            '期初库存': item.initialStock || 0,
            '期内总供应': item.withinPeriodTotalSupply || 0,
            '期内总需求': item.withinPeriodTotalDemand || 0,
            '期内现存量': item.withinPeriodStock || 0,
            '期内是否缺料': item.isWithinPeriodShortage ? '是' : '否',
            '期内最大缺料量': item.withinPeriodMaxShortageQuantity || 0,
            '期外总供应': item.outOfPeriodTotalSupply || 0,
            '期外总需求': item.outOfPeriodTotalDemand || 0,
            '期外现存量': item.outOfPeriodStock || 0,
            '期外是否缺料': item.isOutOfPeriodShortage ? '是' : '否',
            '期外最大缺料量': item.outOfPeriodMaxShortageQuantity || 0,
            '安全库存': item.safetyStock || 0,
            '最小订购量': item.minOrderQuantity || 0
          };

          return row;
        });

        // 创建工作表
        const worksheet = XLSX.utils.json_to_sheet(exportData);
        const workbook = XLSX.utils.book_new();
        
        // 设置列宽
        const colWidths = [
          { wch: 8 },   // 序号
          { wch: 15 },  // 料号
          { wch: 30 },  // 料品名称
          { wch: 30 },  // 规格型号
          { wch: 8 },   // 单位
          { wch: 12 },  // 期初库存
          { wch: 12 },  // 期内总供应
          { wch: 12 },  // 期内总需求
          { wch: 12 },  // 期内现存量
          { wch: 12 },  // 期内是否缺料
          { wch: 15 },  // 期内最大缺料量
          { wch: 12 },  // 期外总供应
          { wch: 12 },  // 期外总需求
          { wch: 12 },  // 期外现存量
          { wch: 12 },  // 期外是否缺料
          { wch: 15 },  // 期外最大缺料量
          { wch: 12 },  // 安全库存
          { wch: 12 }   // 最小订购量
        ];
        worksheet['!cols'] = colWidths;

        XLSX.utils.book_append_sheet(workbook, worksheet, '物管平台数据');

        // 生成文件名
        const dateStr = this.cutoffDate.toISOString().split('T')[0];
        const fileName = `物管平台数据_${dateStr}.xlsx`;

        // 下载文件
        XLSX.writeFile(workbook, fileName);
        
        this.message.success(`成功导出 ${allData.length} 条数据`);
        this.exporting = false;
      },
      error: (error) => {
        this.message.error('导出失败，请稍后重试');
        this.exporting = false;
      }
    });
  }
}

